import audio from '@/assets/file-icon/audio.svg'
import excel from '@/assets/file-icon/excel.svg'
import image from '@/assets/file-icon/image.svg'
import pdf from '@/assets/file-icon/pdf.svg'
import ppt from '@/assets/file-icon/ppt.svg'
import ucode from '@/assets/file-icon/ucode.svg'
import upython from '@/assets/file-icon/upython.svg'
import usim from '@/assets/file-icon/usim.svg'
import video from '@/assets/file-icon/video.svg'
import word from '@/assets/file-icon/word.svg'
import zip from '@/assets/file-icon/zip.svg'

type FileType =
  | 'word'
  | 'ppt'
  | 'pdf'
  | 'excel'
  | 'video'
  | 'zip'
  | 'audio'
  | 'image'
  | 'ucode'
  | 'upython'
  | 'usim'

const acceptTypes: Record<FileType, [string, string[]]> = {
  word: [word, ['doc', 'docx', 'rtf']],
  ppt: [ppt, ['ppt', 'pptx']],
  pdf: [pdf, ['pdf']],
  excel: [excel, ['xls', 'xlsx']],
  video: [video, ['avi', 'mp4', 'mpg', 'mpeg', 'mov', 'rm', 'ram', 'swf', 'flv']],
  zip: [zip, ['rar', 'zip', 'arj']],
  audio: [audio, ['mp3', 'wav', 'wma', 'mov', 'ra']],
  image: [image, ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'ico', 'svg']],
  ucode: [ucode, ['ucd', 'ucdx', 'sb3']],
  upython: [upython, ['ipynb']],
  usim: [usim, ['usim']],
}

export const getFileSuffix = (filename: string) =>
  filename?.split?.('.').reverse?.()?.[0]?.toLocaleLowerCase()

export const getFileName = (filename: string) => filename.replace(/(.*)(\..*)$/, '$1')

export const getFileType = (filename: string): FileType | 'other' => {
  const suffix = getFileSuffix(filename)
  const value = Object.keys(acceptTypes).find((key) =>
    acceptTypes[key as FileType][1].includes(suffix),
  ) as FileType
  return value || 'other'
}

type CallBack = (files: File[]) => void

/**
 * 函数调用方式选择一个文件上传
 * accept: 文件类型 .png,.gif
 * cb: 选中文件确定时的回调
 */
export const importFile = (() => {
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  let callback: CallBack = () => {}
  const inputObj = document.createElement('input')
  inputObj.setAttribute('type', 'file')
  inputObj.setAttribute('name', 'file')
  inputObj.setAttribute('style', 'visibility:hidden')
  inputObj.addEventListener('change', (evt: any) => {
    const files = evt.target.files
    callback(files)
    // 选择完文件后，重置（防止第二次选择同一文件无效）
    evt.target.value = ''
  })
  return function (accept: string, cb: CallBack) {
    callback = cb
    inputObj.setAttribute('accept', accept)
    inputObj.click()
  }
})()

/**
 * 获取url链接中的文件名称，比如http://a.com/111.png，会返回文件名'111'
 * @param url
 * @returns
 */
export const getFileNameFromUrl = (url = '') => {
  const pathArr = decodeURIComponent(url).split('/')
  const fullName = pathArr.pop()
  if (fullName) {
    return fullName.slice(0, fullName.lastIndexOf('.'))
  }
  return ''
}
